package com.zzyl.nursing.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.nursing.domain.NursingTask;
import com.zzyl.nursing.mapper.NursingTaskMapper;
import com.zzyl.nursing.service.INursingTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 护理任务业务层实现类
 *
 * @author 16797
 */
@Service
public class NursingTaskServiceImpl extends ServiceImpl<NursingTaskMapper, NursingTask> implements INursingTaskService {

    @Autowired
    private NursingTaskMapper nursingTaskMapper;

    /**
     * 查询护理任务
     *
     * @param id 护理任务主键
     * @return 护理任务
     */
    @Override
    public NursingTask selectNursingTaskById(Long id) {
        return getById(id);
    }

    /**
     * 查询护理任务列表
     *
     * @param nursingTask 护理任务
     * @return 护理任务
     */
    @Override
    public List<NursingTask> selectNursingTaskList(NursingTask nursingTask) {
        return nursingTaskMapper.selectNursingTaskList(nursingTask);
    }

    /**
     * 新增护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int insertNursingTask(NursingTask nursingTask) {
        return save(nursingTask) ? 1 : 0;
    }

    /**
     * 修改护理任务
     *
     * @param nursingTask 护理任务
     * @return 结果
     */
    @Override
    public int updateNursingTask(NursingTask nursingTask) {
        return updateById(nursingTask) ? 1 : 0;
    }

    /**
     * 批量删除护理任务
     *
     * @param ids 需要删除的护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除护理任务信息
     *
     * @param id 护理任务主键
     * @return 结果
     */
    @Override
    public int deleteNursingTaskById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    // 任务状态常量（更新版）
    public static final int STATUS_CANCELLED = 3;     // 已关闭
    public static final int STATUS_COMPLETED = 2;      // 已执行
    public static final int STATUS_SCHEDULED = 1;      // 待执行

    /**
     * 取消护理任务（实际为“关闭”任务）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelTask(Long taskId, String reason) {
        NursingTask task = nursingTaskMapper.selectById(taskId);
        if (task == null) {
            throw new RuntimeException("护理任务不存在");
        }
        if (task.getStatus() != STATUS_SCHEDULED) {
            throw new RuntimeException("该任务无法取消，当前状态不允许");
        }

        LambdaUpdateWrapper<NursingTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(NursingTask::getId, taskId)
                .set(NursingTask::getStatus, STATUS_CANCELLED) // 设置为 3（已关闭）
                .set(NursingTask::getCancelReason, reason)
                .set(NursingTask::getUpdateTime, LocalDateTime.now())
                .set(NursingTask::getUpdateBy, getCurrentUserId());

        nursingTaskMapper.update(null, updateWrapper);
    }

    /**
     * 执行护理任务
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void executeTask(Long taskId, LocalDateTime estimatedServerTime, String mark, String taskImage) {
        NursingTask task = nursingTaskMapper.selectById(taskId);
        if (task == null) {
            throw new RuntimeException("护理任务不存在");
        }
        if (task.getStatus() != STATUS_SCHEDULED) {
            throw new RuntimeException("该任务无法执行，当前状态不允许");
        }

        LambdaUpdateWrapper<NursingTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(NursingTask::getId, taskId)
                .set(NursingTask::getStatus, STATUS_COMPLETED) // 设置为 2（已执行）
                .set(NursingTask::getMark, mark)
                .set(NursingTask::getTaskImage, taskImage)
                .set(NursingTask::getEstimatedServerTime, estimatedServerTime)
                .set(NursingTask::getUpdateTime, LocalDateTime.now())
                .set(NursingTask::getUpdateBy, getCurrentUserId());

        nursingTaskMapper.update(null, updateWrapper);
    }

    /**
     * 任务改期
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void rescheduleTask(Long taskId, LocalDateTime estimatedServerTime) {
        NursingTask task = nursingTaskMapper.selectById(taskId);
        if (task == null) {
            throw new RuntimeException("护理任务不存在");
        }
        if (task.getStatus() != STATUS_SCHEDULED) {
            throw new RuntimeException("该任务无法改期，当前状态不允许");
        }

        LambdaUpdateWrapper<NursingTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(NursingTask::getId, taskId)
                .set(NursingTask::getEstimatedServerTime, estimatedServerTime)
                .set(NursingTask::getUpdateTime, LocalDateTime.now())
                .set(NursingTask::getUpdateBy, getCurrentUserId());

        nursingTaskMapper.update(null, updateWrapper);
    }

    // ==================== 私有工具方法 ====================

    /**
     * 获取当前登录用户的用户ID（Long类型）
     * 兼容：用户名为数字字符串的情况（如 "123"）
     * 如果无法解析，返回 -1L 表示未知用户
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            return -1L;
        }

        Object principal = authentication.getPrincipal();

        // 如果 principal 是 String（如用户名）
        if (principal instanceof String) {
            String username = (String) principal;
            try {
                return Long.parseLong(username.trim());
            } catch (NumberFormatException e) {
                return -1L;
            }
        }

        return -1L; // 默认未知用户
    }
}